package sensorgui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * Top level GUI object.
 * Constructor creates and shows the entire GUI.
 */
public class AppView implements PropertyChangeListener {
	
	
	private final JLabel elapsedTimeLabel;
    private GridView gd;
    private Grid sensorGd;

	public AppView(Grid sensorGrid) {
	
        sensorGd = sensorGrid;
        
        List <Sensor>sensors = sensorGd.getSensors();
        Iterator <Sensor>iter = sensors.iterator();
        
        while(iter.hasNext()){
        	Sensor sensor = ((Sensor)iter.next());
        	sensor.addPropertyChangeListener(this);
        }
		
		JFrame frame = new JFrame("SensorGrid");
		gd = new GridView(sensorGd);
		frame.add(gd);
		
		// Create a lower panel to show the current status
		JPanel infoPanel = new JPanel();
		infoPanel.setLayout(new FlowLayout());
		infoPanel.add(new JLabel("      "));
		elapsedTimeLabel = new JLabel(getTimeStatus());
		infoPanel.add(elapsedTimeLabel);
		frame.add(infoPanel, BorderLayout.SOUTH);
		
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Finally, show it, and start the timer
		frame.setVisible(true);
		//timer.start();
	}

		
	public void propertyChange(PropertyChangeEvent evt) {
		  System.out.println(evt.getPropertyName() + " changed");
          gd.repaint();

	}
	
	private int elapsedSeconds = 0;
	private int elapsedMinutes = 0;
	private int elapsedHours = 0;
	
	private String getTimeStatus() {
		return String.format("Elapsed time: %02d:%02d:%02d",
				elapsedHours, elapsedMinutes, elapsedSeconds) ;
	}
	
	public void timerUpdate() {
		++elapsedSeconds;
		if (elapsedSeconds >= 60) {
			elapsedSeconds = 0;
			++elapsedMinutes;
			if (elapsedMinutes >= 60) {
				elapsedMinutes = 0;
				++elapsedHours;
			}
		}
		elapsedTimeLabel.setText(getTimeStatus());
	}
}
